import { ChatService } from './ChatService'

/**
 * 聊天管理器
 * 负责处理聊天的业务逻辑，包括状态管理和错误处理
 */
export class ChatManager {
  private chatService: ChatService
  private cleanup: (() => void) | null = null

  constructor(baseUrl?: string) {
    this.chatService = new ChatService(baseUrl)
  }

  /**
   * 检查连接状态
   */
  isConnected(): boolean {
    return this.chatService.isConnected()
  }

  /**
   * 初始化聊天连接
   * @param callbacks - 回调函数集合
   */
  initialize(callbacks: {
    onMessage: (content: string) => void
    onError?: (error: string) => void
  }) {
    try {
      this.cleanup = this.chatService.connect({
        onMessage: (content) => {
          console.log('收到消息:', content)
          callbacks.onMessage(content)
        },
        onError: (error) => {
          console.error('连接错误:', error)
          callbacks.onError?.(error)
        }
      })
    } catch (error) {
      if (error instanceof Error) {
        callbacks.onError?.(error.message)
      }
    }
  }

  /**
   * 发送消息
   * @param message - 消息内容
   * @param conversationId - 可选的会话ID
   */
  async sendMessage(message: string, conversationId?: number) {
    try {
      const response = await this.chatService.sendMessage(message, conversationId)
      console.log('发送成功:', response)
      return response
    } catch (error) {
      console.error('发送失败:', error)
      throw error
    }
  }

  /**
   * 获取历史记录
   * @param conversationId - 会话ID
   */
  async getHistory(conversationId: number) {
    try {
      return await this.chatService.getHistory(conversationId)
    } catch (error) {
      console.error('获取历史记录失败:', error)
      throw error
    }
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (this.cleanup) {
      this.cleanup()
      this.cleanup = null
    }
  }
} 